package com.itheima.security.distributed.uaa.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

/**
 * @author xiaoxiaokui
 * @date 2019/11/26
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * @Description: 将客户端信息存储到数据库
     * @Param: [dateSource]
     * @return: org.springframework.security.oauth2.provider.ClientDetailsService
     * @Author: xiaoxiaokui
     * @Date: 2019/12/2
     */
    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource) {
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        ((JdbcClientDetailsService) clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }

    /**
     * @Description: 配置客户端详情信息服务
     * 用来配置客户端详情信息服务（ClientDetailsService），
     * 客户端详情信息在这里进行初始化，你能够把客户端详情信息写死在这里
     * 或者是通过数据库来存储调取详情信息。
     * @Param: [clients]
     * @return: void
     * @Author: xiaoxiaokui
     * @Date: 2019/11/26
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);

        // 暂时使用内存方式
//        clients.inMemory()
//                // client_id
//                .withClient("c1")
//                // 客户端密钥
//                .secret(new BCryptPasswordEncoder().encode("secret"))
//                // 资源列表
//                .resourceIds("res1")
//                // 该客户端授权的类型
//                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
//                // 允许的授权范围
//                .scopes("all")
//                // false 跳转到授权页面
//                .autoApprove(false)
//                // 加上验证回调地址
//                .redirectUris("http://www.baidu.com");
    }

    /**
     * @Description: 令牌管理服务
     * @Param: []
     * @return: org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices
     * @Author: xiaoxiaokui
     * @Date: 2019/11/26
     */
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices service = new DefaultTokenServices();
        // 客户端信息服务
        service.setClientDetailsService(clientDetailsService);
        // 是否产生刷新令牌
        service.setSupportRefreshToken(true);
        // 令牌存储策略
        service.setTokenStore(tokenStore);

        // 令牌增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        service.setTokenEnhancer(tokenEnhancerChain);

        // 令牌默认有效期2小时
        service.setAccessTokenValiditySeconds(7200);
        // 刷新令牌默认有效期3天
        service.setRefreshTokenValiditySeconds(259200);
        return service;
    }

    /**
     * @Description: 令牌访问端点
     * 用来配置令牌（token）的访问端点和令牌服务（tokenServices）。
     * @Param: [endpoints]
     * @return: void
     * @Author: xiaoxiaokui
     * @Date: 2019/11/26
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // 设置认证管理器（密码模式所需要）
                .authenticationManager(authenticationManager)
                // 授权码服务
                .authorizationCodeServices(authorizationCodeServices)
                // 令牌管理服务
                .tokenServices(tokenService())
                // 端点允许post提交访问令牌端点
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    /**
     * @Description: 令牌访问端点安全约束
     * 用来配置令牌端点的安全约束
     * @Param: [security]
     * @return: void
     * @Author: xiaoxiaokui
     * @Date: 2019/11/26
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // /oauth/token_key是公开
                .tokenKeyAccess("permitAll()")
                // /oauth/check_token公开
                .checkTokenAccess("permitAll()")
                // 表单认证（申请令牌）
                .allowFormAuthenticationForClients();
    }

    /**
     * @Description: 设置授权码模式的授权码如何存取，暂时用内存方式
     * @Param: []
     * @return: org.springframework.security.oauth2.provider.code.AuthorizationCodeServices
     * @Author: xiaoxiaokui
     * @Date: 2019/11/26
     */
//    @Bean
//    public AuthorizationCodeServices authorizationCodeServices() {
//        return new InMemoryAuthorizationCodeServices();
//    }
    
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
        // 设置授权码模式的授权码如何存取
        return new JdbcAuthorizationCodeServices(dataSource);
    }
}
